extends CharacterBody2D

@export var speed_主角速度 : float = 200
@export var animator_主角动画 : AnimatedSprite2D
@export var node_子弹节点 : PackedScene

var is_die_是否死亡 : bool = false

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	animator_主角动画 = get_node("AnimatedSprite2D") as AnimatedSprite2D
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	pass


func _physics_process(_delta: float) -> void:
	if is_die_是否死亡:
		return
	
	# 获取用户键盘输入, 然后计算主角移动距离
	velocity = Input.get_vector('left', 'right', 'up', 'down') * speed_主角速度
	
	# 判断主角是否移动, 根据判断播放不同的动画
	if velocity == Vector2.ZERO:
		animator_主角动画.play('待机')
		if $"AudioStreamPlayer_移动".playing:
			$"AudioStreamPlayer_移动".stop()
	else:
		animator_主角动画.play('移动')
		if !$"AudioStreamPlayer_移动".playing:
			$"AudioStreamPlayer_移动".play()
	
	move_and_slide()
	pass
	
# 游戏结束
func game_over():
	if !is_die_是否死亡:
		is_die_是否死亡 = true
		animator_主角动画.play('死亡')
		if $"AudioStreamPlayer_移动".playing:
			$"AudioStreamPlayer_移动".stop()
		$"AudioStreamPlayer_死亡".play()
		# 启动死亡延迟计时器, 解释结束后跳转开始菜单
		get_node("Timer_死亡延迟").start()
	pass

func _on_timer_子弹创建_timeout() -> void:
	# 判断主角移动或死亡状态, 根据状态判断是否发射子弹
	if velocity != Vector2.ZERO or is_die_是否死亡:
		return
	
	var node_子弹实例 = node_子弹节点.instantiate()
	node_子弹实例.position = position + Vector2(17, 3)
	get_tree().current_scene.add_child(node_子弹实例)
	
	pass # Replace with function body.


func _on_timer_死亡延迟_timeout() -> void:
	get_tree().change_scene_to_file("res://scene_场景/scene_开始菜单.tscn")
	pass # Replace with function body.
